package com.pdwl.cashoutpay.controller;

import com.pdwl.cashoutpay.entity.Merchant;
import com.pdwl.cashoutpay.entity.Trade;
import com.pdwl.cashoutpay.entity.res.BaseEntity;
import com.pdwl.cashoutpay.entity.res.TradeRes;
import com.pdwl.cashoutpay.service.MerchantRegisterService;
import com.pdwl.cashoutpay.service.OrderService;
import com.pdwl.cashoutpay.util.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("fastPayRouter")
public class CostMail {

    @Value("${costMailUrl}")
    private String costMailUrl;

    @Value("${publicKey}")
    private String publicKey;

    @Value("${costMailNotifyUrl}")
    private String costMailNotifyUrl;

    @Autowired
    MerchantRegisterService merchantRegisterService;
    @Autowired
    OrderService orderService;


    @RequestMapping(value = "consumeSMS")
    public void fastPayRouter(HttpServletRequest request, HttpServletResponse response) throws Exception {
        LogUtils.logInfo("交易开始，发送短信");
        response.setHeader("Content-type", "textml;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        JSONObject map = JsonUtil.getJson(request);

        BaseEntity baseEntity = new BaseEntity();

        if (map.getString("sign").equals(Sign.getSign(map))) {
            aaa:{
                Trade trade = httpPayToMerchant(map);

                if (!CheckBankCard.checkBankCard(trade.getCriditno())) {
                    LogUtils.logInfo("请核对银行卡信息！");
                    baseEntity.setError_code("20006");
                    baseEntity.setError_message("请核对银行卡信息！");
                    break aaa;
                }

                if (!AccountValidatorUtil.isMobile(trade.getBankphoneno())) {
                    LogUtils.logInfo("请核对手机号！");
                    baseEntity.setError_code("20007");
                    baseEntity.setError_message("请核对手机号！");
                    break aaa;
                }

                orderService.add(trade);
                baseEntity = costMail(trade);
            }
        } else {
            LogUtils.logInfo("验签失败！");
            baseEntity.setError_code("20005");
            baseEntity.setError_message("验签失败，请重新验签！");
        }

        JSONObject json = JSONObject.fromObject(baseEntity);//将java对象转换为json对象
        String res = json.toString();
        response.getWriter().write(res);
    }

    /**
     * 将http请求转换成标准请求类
     *
     * @param map
     * @return
     */
    private Trade httpPayToMerchant(JSONObject map) {
        String outMerchantCode = map.getString("outMerchantCode");
        Merchant merchant = merchantRegisterService.queryByOutMerchCode(outMerchantCode);
        String subMerchCode = merchant.getSubmerchantcode();
        String ourOrderId = map.getString("orderNo") + TimeUtil.getTime("yyyyMMddHHmmss");
        Trade order = new Trade();
        order.setSubmerchcode(subMerchCode);
        order.setOrderid(map.getString("orderNo"));
        order.setOurorderid(ourOrderId);
        order.setAmount(map.getString("amount"));
        order.setNotifyurl(map.getString("notifyUrl"));
        order.setBankphoneno(map.getString("bankPhoneNo"));
        order.setCriditno(map.getString("criditNo"));
        order.setCvv(map.getString("cvv"));
        order.setExpiredate(map.getString("expireDate"));
        order.setStatus("00");
        order.setDaytime(TimeUtil.getTime("yyyyMMdd"));
        order.setHoutime(TimeUtil.getTime("yyyyMMddHHmmss"));
        order.setTraderate("");//给我们的费率
        order.setSubtraderate("");//代理商费率
        order.setThirdtraderate("");
        return order;
    }

    /**
     * 请求上游，短信消费
     *
     * @param trade
     * @return
     * @throws Exception
     */
    public BaseEntity costMail(Trade trade) throws Exception {
        BaseEntity baseEntity = new BaseEntity();

//        短信消费
        Map payReq = new HashMap<String, String>();
        payReq.put("orderNo", trade.getOurorderid()); //商户订单号
        payReq.put("amount", trade.getAmount()); //交易金额
        payReq.put("merchCode", ContanGobal.OURMERCHANTCODE); //接入商编号
        payReq.put("subMerchCode", trade.getSubmerchcode()); //莱付商户号
        payReq.put("goodsName", "消费"); //商品名称
        payReq.put("channelCode", "fastSoopay"); //通道编码
        payReq.put("typeCode", "T0"); //交易类型
        payReq.put("notifyUrl", costMailNotifyUrl); //回调地址
        payReq.put("remark", "1"); //备注
        payReq.put("criditNo", trade.getCriditno()); //信用卡号
        payReq.put("bankPhoneNo", trade.getBankphoneno()); //银行卡预留手机
        String cvv = RSAUtils.encryptByPublicKey(trade.getCvv().getBytes(), publicKey);
        payReq.put("cvv", cvv);
        payReq.put("expireDate", trade.getExpiredate()); //有效期

        LogUtils.logInfo("开始交易，发送短信，发送数据：" + payReq.toString());

        String res = HttpUtil.formUpload(costMailUrl, payReq);
        LogUtils.logInfo("开始交易，发送短信，返回数据：" + res.toString());

        org.json.JSONObject jsonRes = new org.json.JSONObject(res);
        String error_code = (String) jsonRes.getString("errorCode");
        String error_message = (String) jsonRes.getString("errorMessage");
        if ("000000".equals(error_code)) {
            String channel = JsonUtil.getChannelCode(res);
            trade.setToporderid(channel);
            orderService.update(trade);

            TradeRes tradeRes = new TradeRes();
            tradeRes.setOrderid(trade.getOrderid());
            tradeRes.setOurorderid(trade.getOurorderid());
            tradeRes.setAmount(trade.getAmount());
            tradeRes.setNotifyurl(trade.getNotifyurl());
            tradeRes.setCriditno(trade.getCriditno());
            tradeRes.setBankphoneno(trade.getBankphoneno());
            tradeRes.setStatus(trade.getStatus());
            tradeRes.setMessage(trade.getMessage());

            baseEntity.setError_code("1");
            baseEntity.setError_message(error_message);
            baseEntity.setData(tradeRes);
        } else {
            baseEntity.setError_code("2");
            baseEntity.setError_message(error_message);
        }

        return baseEntity;
    }


}
